import os

from utils import select_util, excel_util, doc_util, read_config, parse_util
from service.data_service import stock_dict
from database.mapper import funds_info, boards_info


def filtrate_correlation():
    print('筛选板块关联度')
    doc_path = os.path.join(read_config.data_path, 'common', 'config')
    doc_name = select_util.select_doc_name(doc_path)
    if doc_name == '' or doc_name == '00':
        print('输入错误')
        return
    doc_info = doc_util.get_path_doc_info(os.path.join(doc_path, doc_name))
    gen_result_excel(doc_info, doc_name)


def filtrate_path(doc_path, doc_name):
    print('筛选板块关联度')
    doc_name = select_util.select_doc_name(doc_path)
    doc_info = select_util.select_by_name(doc_path, doc_name)
    gen_result_excel(doc_info, doc_name)


# 生成新的板块
def gen_plate(path):
    file_names = {}
    for root, dirs, files in os.walk(path):
        for file in files:
            infos = file.split('.')
            file_names[infos[0]] = file
    while 1:
        name_w = input('请输入新的名称(例:10.军工)')
        if name_w.split('.')[0] in file_names.keys():
            print('序号重复,选择文件')
            name_w = file_names[name_w]
            break
        elif len(name_w.split('.')) != 2:
            print('格式不符合')
        else:
            break
    file_w = open(path + name_w, mode='w', encoding='utf-8')
    source_path = read_config.data_path + '\\common\\plates\\'
    while 1:
        print(source_path)
        source_path_len = len(source_path.split('\\'))
        # 沪深板块
        file_names = doc_util.get_file_path_names(source_path)
        if len(file_names) == 1:
            if os.path.exists(source_path):
                source_path = file_names[0]
                break
            else:
                source_path = read_config.data_path + '\\common\\plates\\'
                print('路径错误重新输入')
                continue
        path_dict = {}
        for file_path_name in file_names:
            if len(file_path_name.split('\\')) >= (source_path_len + 1):
                path_dict[file_path_name.split('\\')[source_path_len - 1]] = 1
        for file_path in path_dict:
            print(file_path)
        print(source_path)
        source_path_add = input('*******请输入增加的路径:')
        for file_path_name in path_dict:
            if file_path_name.__contains__(source_path_add):
                source_path += (file_path_name + '\\')
                break
    file_r = open(source_path, mode='r', encoding='utf-8')
    info_r = doc_util.get_doc_info(file_r)
    for info in info_r:
        code = eval(info)['f12']
        if code not in stock_dict:
            continue
        file_w.write(str(stock_dict[code]) + '\n')
    file_r.close()
    file_w.close()
    return name_w


def gen_result_excel(doc_info, doc_name):
    result = {}
    # parse_util.list_dict_to_list(doc_info, 'code')
    result_dict = {}
    for stock_info in doc_info:
        fs_list = funds_info.select_by_stock_code(stock_info.get('code'))
        for fs in fs_list:
            fund_code = fs.get('fund_code')
            if fund_code not in result_dict.keys():
                result_dict[fund_code] = []
            result_dict[fund_code].append(fs)
    doc_dict = parse_util.list_to_dict(doc_info, 'code')
    content_arr = []
    # content_arr_ext = [['--', '--', '--', '--', '--', '--']]
    for key in result_dict.keys():
        fs_list = result_dict.get(key)
        row_arr_ext = []
        ratio = 0
        sum_val = 0
        for fs in fs_list:
            ratio += fs.get('ratio')
            sum_val += fs.get('stock_val')
            row_arr_ext.append(fs.get('code'))
            row_arr_ext.append(fs.get('name'))
            row_arr_ext.append('股票')
            row_arr_ext.append(doc_dict.get(fs.get('code')).get('total_val'))
            row_arr_ext.append(fs.get('stock_val'))
            row_arr_ext.append(fs.get('ratio'))
        content_arr.append([key, fs_list[0].get('fund_name'), fs_list[0].get('type'),
                            fs_list[0].get('total_val'), sum_val, ratio])
        # content_arr_ext.append(row_arr_ext)
    content_arr = sorted(content_arr, key=lambda x: (x[5]), reverse=True)
    path = os.path.join(read_config.data_path, 'result', '筛选基金')
    excel_util.gen_an_excel(path, doc_name, '', [['编码', '名称', '类型', '总额', '持有', '占比']] + content_arr)


if __name__ == '__main__':
    print('start')
    filtrate_correlation()
    print('end')
